<?php
/*
 * @project CreativeFramework
 * @version <#RELEASE_VERSION#>
 * @license GNU Lesser General Public License
 * @author Jimmie Lin
 */

class DB{
	public function __construct(){
		// Lets do it
		$engine = DB_ENGINE;
		if(file_exists(CORE_PATH."drivers/{$engine}.php")){
			require_once(CORE_PATH."drivers/{$engine}.php");
			$this->Driver = new Driver;
		}
		else{
			throwFatalError("Cannot find Database Driver {$engine} in drivers path, is the engine present?");
		}
		// Do it.
		$this->Driver->Connect();
		// Localized queries
		$this->localizedQueries = array();
		$this->queryType = $this->Driver->usequeries;
	}
	
	/**
	 * localizedQuery
	 * Run a raw SQL query specially made for a specific engine.
	 * If the query is not localized in that engine, an fatal error will be thrown.
	 * Returns the Query return value in that engine if success, otherwise void.
	 * @param string query_id Identifier/Key for the query
	 * @return mixed (resource/object if success, otherwise void)
	 */
	function localizedQuery($query_id, $application = APPLICATION) {

		if(!isset($this->loadedLocalizedQueries[$application])) {
			// Load this application's localized queries!
			if(file_exists(APPLICATION_PATH."universal".DIRECTORY_SEPARATOR.$application.DIRECTORY_SEPARATOR."localizedQueries.php")) {
				require_once(APPLICATION_PATH."universal".DIRECTORY_SEPARATOR.$application.DIRECTORY_SEPARATOR."localizedQueries.php");
				// Now that's done, get it
				$this->loadedLocalizedQueries[$application] = true;
			}
			else {
				$this->loadedLocalizedQueries[$application] = true;
				return;
			}
		}
		
		if(!isset($this->localizedQueries[$this->queryType][$query_id])) {
			return;
		}
		else {
			return $this->Driver->query($this->localizedQueries[$this->queryType][$query_id]);
		}
	}
	
	/**
	 * getQueryCount
	 * Get the number of queries executed up to the moment of the function call.
	 * @return int
	 */
	public function getQueryCount(){
		return intval($this->Driver->querycount);
	}
}
